﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace NCRGEA.AAL
{
    public static class UAL
    {
        public static User AuthenticateUser(string uName, string pWord)
        {
            string qry = string.Format("SELECT * FROM usrAccounts WHERE UPPER(Username)=UPPER('{0}') AND UPPER(Password)=UPPER('{1}') AND Active=1", uName, pWord);
            DataTable results = AAL.DAL.ExecuteQuery(qry);
            if (results != null && results.Rows.Count == 1)
            {
                string u = results.Rows[0]["Username"].ToString();
                int sid = (int)results.Rows[0]["StaffID"];
                string fN = results.Rows[0]["FirstName"].ToString();
                string lN = results.Rows[0]["LastName"].ToString();
                bool a = (bool)results.Rows[0]["Active"];

                return new User(u, sid, fN, lN, a);
            }
            return null;
        }

        public static int? GetPlanID(int MemberID, int ProgramID)
        {
            string sqlQry = @"SELECT PlanID FROM memPlans WHERE MemberID=@MemberID AND ProgramID=@ProgramID AND Active=1";
            SqlParameter[] sParamArray = new SqlParameter[3];
            sParamArray[0] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            sParamArray[1] = new SqlParameter("@ProgramID", ProgramID) { SqlDbType = SqlDbType.Int };
            DataTable result = DAL.ExecuteQuery(sqlQry, sParamArray);
            if (result == null || result.Rows.Count == 0)
                return null;
            return (int)result.Rows[0]["PlanID"];
        }

        public static void AddParticipantToPlan(int PlanID, string FirstName, string LastName, DateTime StartDate, int Relation)
        {
            string sqlQry = @"INSERT INTO memParticipants (PlanID, FirstName, LastName, Relation, StartDate, Active) VALUES 
                                (@PlanID, @FirstName, @LastName, @Relation, @StartDate, 1)";
            SqlParameter[] sParamArray = new SqlParameter[5];
            sParamArray[0] = new SqlParameter("@PlanID", PlanID) { SqlDbType = SqlDbType.Int };
            sParamArray[1] = new SqlParameter("@FirstName", FirstName) { SqlDbType = SqlDbType.VarChar, Size=20 };
            sParamArray[2] = new SqlParameter("@LastName", LastName) { SqlDbType = SqlDbType.VarChar, Size = 20 };
            sParamArray[3] = new SqlParameter("@Relation", Relation) { SqlDbType = SqlDbType.Int };
            sParamArray[4] = new SqlParameter("@StartDate", StartDate) { SqlDbType = SqlDbType.Date };
            int result = DAL.ExecuteNonQuery(sqlQry, sParamArray);
        }

        public static bool RegisterProgram(int ProgramID, int MemberID, DateTime StartDate, DataTable participants)
        {
            //Add the plan
            string sqlQry = @"INSERT INTO memPlans (ProgramID, MemberID, StartDate, Active) VALUES (@ProgramID, @MemberID, @StartDate, 1)";
            SqlParameter[] sParamArray = new SqlParameter[3];
            sParamArray[0] = new SqlParameter("@ProgramID", ProgramID) { SqlDbType = SqlDbType.Int };
            sParamArray[1] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            sParamArray[2] = new SqlParameter("@StartDate", StartDate) { SqlDbType = SqlDbType.Date };
            int result = DAL.ExecuteNonQuery(sqlQry, sParamArray);
            if (result != 1)
                return false;

            //Get the Plan ID
            int? PlanID = GetPlanID(MemberID, ProgramID);
            if (PlanID == null)
                return false;   //Something went wrong..

            if (participants != null && participants.Rows.Count > 0)
            {
                //Validate that our data table has the required columns
                foreach (string a in (new string[] { "FirstName", "LastName", "StartDate", "Relation" }))
                    if (!participants.Columns.Contains(a))
                        return false;

                //Add the participants to the plan
                foreach (DataRow dr in participants.Rows)
                {
                    string fName = dr["FirstName"].ToString();
                    string lName = dr["LastName"].ToString();
                    DateTime sDate = (DateTime)dr["StartDate"];
                    int Relation = (int)dr["Relation"];
                    AddParticipantToPlan(PlanID.Value, fName, lName, sDate, Relation);
                }
            }
            UpdateProgramFlag(MemberID, ProgramID, "A");
            return true;
        }

        public static bool ValidateSSN_Enrollment(string ssn)
        {
            if (string.IsNullOrWhiteSpace(ssn))
                return false;
            int s;
            if (!int.TryParse(ssn, out s))
                return false;
            if (ssn.Length != 9)
                return false;
            return true;
        }

        public static void UpdateProgramFlag(int MemberID, int ProgramID, string type)
        {
            if (string.IsNullOrWhiteSpace(type))
                return;
            int? ProgramTypeID = GetProgramCategory(ProgramID);
            if (ProgramTypeID == null)
            {
                Logger.Log("ProgramTypeID was null in UpdateProgramFlag(" + MemberID + "," + ProgramID + "," + type + ")!");
                return;
            }

            string ColumnName = null;
            if (ProgramTypeID.Value == 0)       //Dental
                ColumnName = "DentalFlag";
            else if (ProgramTypeID.Value == 1)  //Vision
                ColumnName = "VisionFlag";
            else
            {
                //WTF is this?
                Logger.Log("Encountered an unknown ProgramTypeID!: " + ProgramTypeID.Value + " - MemberID: " + MemberID);
                return;
            }

            string sqlQry = string.Format(@"SELECT {0} FROM memInfo WHERE MemberID=@MemberID", ColumnName);
            SqlParameter[] sParamArray = new SqlParameter[1];
            sParamArray[0] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            DataTable result = DAL.ExecuteQuery(sqlQry, sParamArray);
            if (result == null || result.Rows.Count != 1)
            {
                Logger.Log("Null value or !=1 rowcount while selecting '" + ColumnName + "' for MemberID: " + MemberID);
                return;
            }
            
            /*KEY:
             *      A U D     <- (Old) ->
             *      _______
             *    A|A|U|U|A|
             *    U|A|U|U|A|
             *    D| |D|D| |
             *     |A|U|D| |
             *     
             * 
             * 
             * 
             *   ^
             *   |
             *   
             *   N
             *   e
             *   w
             *   
             *   |
             *   v
             */  




            string Flag = result.Rows[0][ColumnName].ToString();
            string UpdateFlag = Flag;
            switch (Flag)
            {
                case "":
                    switch (type)
                    {
                        case "":
                            UpdateFlag = "";
                            break;
                        case "A":
                            UpdateFlag = "A";
                            break;
                        case "U":
                            UpdateFlag = "A";
                            break;
                        case "D":
                            UpdateFlag = "";
                            break;
                    }
                    break;
                case "A":
                    switch (type)
                    {
                        case "":
                            UpdateFlag = "A";
                            break;
                        case "A":
                            UpdateFlag = "A";
                            break;
                        case "U":
                            UpdateFlag = "A";
                            break;
                        case "D":
                            UpdateFlag = "";
                            break;
                    }
                    break;
                case "U":
                    switch (type)
                    {
                        case "":
                            UpdateFlag = "U";
                            break;
                        case "A":
                            UpdateFlag = "U";
                            break;
                        case "U":
                            UpdateFlag = "U";
                            break;
                        case "D":
                            UpdateFlag = "D";
                            break;
                    }
                    break;
                case "D":
                    switch (type)
                    {
                        case "":
                            UpdateFlag = "D";
                            break;
                        case "A":
                            UpdateFlag = "U";
                            break;
                        case "U":
                            UpdateFlag = "U";
                            break;
                        case "D":
                            UpdateFlag = "D";
                            break;
                    }
                    break;
                default:
                    Logger.Log("Encountered a '" + ColumnName + "' that wasn't '', 'A', 'U', or 'D'! Was: " + Flag + " for MemberID: " + MemberID);
                    break;
            }
            Logger.Log("Updating Member's " + ColumnName + " From '" + Flag + "' to '" + UpdateFlag + "'!");
            string updateQuery = string.Format(@"UPDATE memInfo SET {0}=@UpdateFlag WHERE MemberID=@MemberID", ColumnName);
            SqlParameter[] sParamArr = new SqlParameter[2];
            sParamArr[0] = new SqlParameter("@UpdateFlag", UpdateFlag) { SqlDbType = SqlDbType.Char, Size = 1 };
            sParamArr[1] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            int iResult = DAL.ExecuteNonQuery(updateQuery, sParamArr);
            if (iResult != 1)
                Logger.Log("Attempted to update member's " + ColumnName + " but " + iResult + " rows were affected instead of 1!");
        }

        public static int? GetProgramCategory(int ProgramID)
        {
            string sqlQry = @"SELECT ProgramTypeID FROM memPrograms WHERE ProgramID=@ProgramID";
            SqlParameter[] sParamArray = new SqlParameter[1];
            sParamArray[0] = new SqlParameter("@ProgramID", ProgramID) { SqlDbType = SqlDbType.Int };
            DataTable result = DAL.ExecuteQuery(sqlQry, sParamArray);
            if (result == null || result.Rows.Count == 0)
                return null;
            int val = (int)result.Rows[0]["ProgramTypeID"];
            return val;
        }

        public static bool IsMemberEnrolled(int MemberID)
        {
            string sqlQry = @"SELECT Enrolled FROM memInfo WHERE MemberID = @MemberID";
            SqlParameter[] sParamArray = new SqlParameter[1];
            sParamArray[0] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            DataTable result = DAL.ExecuteQuery(sqlQry, sParamArray);
            if (result == null || result.Rows.Count == 0 || !(bool)result.Rows[0]["Enrolled"])
                return false;
            return true;
        }

        public static bool ValidateSSNChange(string SSN, int MemberID)
        {
            if (string.IsNullOrWhiteSpace(SSN))
                return false;
            string sqlQry = @"SELECT SSN FROM memInfo WHERE SSN=@SSN AND MemberID <> @MemberID";
            SqlParameter[] sParamArray = new SqlParameter[2];
            sParamArray[0] = new SqlParameter("@SSN", SSN) { SqlDbType = SqlDbType.VarChar, Size = 9 };
            sParamArray[1] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            DataTable result = DAL.ExecuteQuery(sqlQry, sParamArray);
            if (result == null)
                return false;   //An error occurred. Unsure if SSN can be changed.
            if (result.Rows.Count == 0)
                return true;
            return false;
        }

        public static void CreateMemberLog(int StaffID, int MemberID, string Message)
        {
            string sqlQry = @"INSERT INTO logActions (StaffID, MemberID, Date, Description) VALUES (@StaffID, @MemberID, GETDATE(), @Description)";
            SqlParameter[] sParamArray = new SqlParameter[3];
            sParamArray[0] = new SqlParameter("@StaffID", StaffID) { SqlDbType = SqlDbType.Int };
            sParamArray[1] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            sParamArray[2] = new SqlParameter("@Description", Message) { SqlDbType = SqlDbType.VarChar, IsNullable = true };
            int result = DAL.ExecuteNonQuery(sqlQry, sParamArray);
            return;
        }

        public static DateTime? GetMemberRenewalDate(int MemberID)
        {
            string sqlQry = @"SELECT RenewalDate FROM memInfo WHERE MemberID=@MemberID";
            SqlParameter[] sParamArray = new SqlParameter[1];
            sParamArray[0] = new SqlParameter("@MemberID", MemberID);
            DataTable result = DAL.ExecuteQuery(sqlQry, sParamArray);
            if (result == null || result.Rows.Count != 1)
                return null;
            if (result.Rows[0]["RenewalDate"] == null)
                return null;
            if (!(result.Rows[0]["RenewalDate"] is DateTime))
                return null;
            return (DateTime)result.Rows[0]["RenewalDate"];
        }

        public static string GetMemberStatus(int MemberID)
        {
            string sqlQry = @"SELECT mI.TypeID, mT.Name FROM memInfo mI INNER JOIN memTypes mT ON mI.TypeID=mT.TypeID WHERE mI.MemberID=@MemberID";
            SqlParameter[] sParamArray = new SqlParameter[1];
            sParamArray[0] = new SqlParameter("@MemberID", MemberID);
            DataTable result = DAL.ExecuteQuery(sqlQry, sParamArray);
            if (result == null || result.Rows.Count != 1)
                return null;
            return result.Rows[0]["Name"].ToString();
        }

        public static bool UpdateRenewalDate(int MemberID, DateTime RenewalDate)
        {
            string updateQuery = @"UPDATE memInfo SET RenewalDate=@RenewalDate WHERE MemberID=@MemberID";
            SqlParameter[] sParamArray = new SqlParameter[2];
            sParamArray[0] = new SqlParameter("@RenewalDate", RenewalDate) { SqlDbType = SqlDbType.Date };
            sParamArray[1] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            int result = AAL.DAL.ExecuteNonQuery(updateQuery, sParamArray);
            if (result != 1)
            {
                Logger.Log("Affected rows==" + result + " while update the renewal date! MemberID: " + MemberID);
                return false;
            }
            return true;
        }


        /// <summary>
        /// Saves a payment for a member and updates them to 'Active' with 0 followups.
        /// </summary>
        /// <param name="MemberID">The MemberID</param>
        /// <param name="MethodID">The Method (Cash, Check, Credit)</param>
        /// <param name="RefNo">The Reference Number (Check#, card CVV2)</param>
        /// <param name="Amount">The Payment Amount</param>
        /// <param name="Date">The Payment Date (Not necessarily today)</param>
        /// <param name="StaffID">The Staff ID making the payment</param>
        /// <param name="PayTypeID">The Payment Type (Dues, Dental, Vision)</param>
        /// <returns>Returns true if successful, otherwise returns false.</returns>
        public static bool SavePayment(int MemberID, int MethodID, int? RefNo, double Amount, DateTime Date, int StaffID, int PayTypeID)
        {
            string insertQuery = @"INSERT INTO payments (MemberID, MethodID, ReferenceNumber, Amount, Date, StaffID, PayTypeID)
                                   VALUES (@MemberID, @MethodID, @ReferenceNumber, @Amount, @Date, @StaffID, @PayTypeID)";
            object ReferenceNumber;
            if (RefNo == null)
                ReferenceNumber = DBNull.Value;
            else
                ReferenceNumber = RefNo.Value;

            SqlParameter[] sParamArray = new SqlParameter[7];
            sParamArray[0] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            sParamArray[1] = new SqlParameter("@MethodID", MethodID) { SqlDbType = SqlDbType.Int };
            sParamArray[2] = new SqlParameter("@ReferenceNumber", ReferenceNumber) { SqlDbType = SqlDbType.Int, IsNullable = true };
            sParamArray[3] = new SqlParameter("@Amount", Amount) { SqlDbType = SqlDbType.Decimal };
            sParamArray[4] = new SqlParameter("@Date", Date) { SqlDbType = SqlDbType.DateTime };
            sParamArray[5] = new SqlParameter("@StaffID", StaffID) { SqlDbType = SqlDbType.Int };
            sParamArray[6] = new SqlParameter("@PayTypeID", PayTypeID) { SqlDbType = SqlDbType.Int };
            int result = AAL.DAL.ExecuteNonQuery(insertQuery, sParamArray);
            if (result != 1)
            {
                Logger.Log("Affected rows==" + result + " while adding a payment! MemberID: " + MemberID);
                return false;
            }

            //Update the member to Active and set NumFollowups to 0
            string updateQuery = @"UPDATE memInfo SET TypeID=1, NumFollowups=0 WHERE MemberID=@MemberID";
            SqlParameter[] sParamArr = new SqlParameter[1];
            sParamArr[0] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            result = DAL.ExecuteNonQuery(updateQuery, sParamArr);
            if (result != 1)
            {
                Logger.Log("Affected rows=== "+ result + " while updating a member to 'Active' and setting NumFollowups==0! MemberID: " + MemberID);
                return false;
            }
            return true;
        }

        public static int? GetProgramTypeIDForPlan(int PlanID)
        {
            int? result = null;
            string q = @"SELECT ProgramTypeID FROM memPlans pl INNER JOIN memPrograms pr ON pl.ProgramID=pr.ProgramID WHERE pl.PlanID=" + PlanID;
            DataTable qTbl = DAL.ExecuteQuery(q, null);
            if (qTbl != null && qTbl.Rows.Count == 1)
                result = (int)qTbl.Rows[0][0];
            return result;
        }


        [Obsolete("This should be removed ASAP. Any functionality that relies on this is incorrect!")]
        public static int? GetMemberIDFromSSN(string SSN)
        {
            SqlParameter[] sParamArr = new SqlParameter[1];
            SqlParameter sParam = new SqlParameter("@SSN", SSN) { SqlDbType = SqlDbType.VarChar, Size = 9 };
            sParamArr[0] = sParam;
            DataTable tbl = AAL.DAL.ExecuteQuery("SELECT MemberID FROM memInfo WHERE SSN=@SSN", sParamArr);
            
            if (tbl == null || tbl.Rows.Count == 0)
                return null;
            int? result = null;
            try
            {
                result = (int)tbl.Rows[0]["MemberID"];
            }
            catch (Exception eX)
            {
                Logger.Log("Couldn't GetMemberIDFromSSN: " + eX.Message);
            }
            return result;
        }

        public static string GetSSN(int MemberID)
        {
            string sqlQry = @"SELECT SSN FROM memInfo WHERE MemberID=@MemberID";
            SqlParameter[] sParamArr = new SqlParameter[1];
            sParamArr[0] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            DataTable tbl = AAL.DAL.ExecuteQuery(sqlQry, sParamArr);
            if (tbl == null || tbl.Rows.Count != 1)
                return null;
            if (tbl.Rows[0]["SSN"] == DBNull.Value || tbl.Rows[0]["SSN"] == null)
                return null;
            return tbl.Rows[0]["SSN"].ToString();
        }

        public static bool RemovePlan(int PlanID, int MemberID)
        {
            string sqlRemoveParticipants = @"DELETE FROM memParticipants WHERE PlanID=" + PlanID;
            string sqlRemovePlan = @"DELETE FROM memPlans WHERE PlanID=" + PlanID;
            int? PlanType = GetProgramTypeIDForPlan(PlanID);
            if (PlanType == null)
            {
                Logger.Log("ERROR: Couldn't map a PlanID to a ProgramTypeID for PlanID: '" + PlanID + "'. Plan was not removed.");
                return false;
            }

            int partResult = DAL.ExecuteNonQuery(sqlRemoveParticipants);
            int planResult = DAL.ExecuteNonQuery(sqlRemovePlan);
            if (planResult != 1)
            {
                Logger.Log("Removed Plan with PlanID '" + PlanID + "' but no rows were affected! Aborting. " + partResult + " participant rows were already deleted!");
                return false;
            }

            string ColumnName = PlanType == 0 ? "DentalFlag" : "VisionFlag";
            string sqlGetMemberFlag = string.Format(@"SELECT {0} FROM memInfo WHERE MemberID={1}",ColumnName, MemberID);

            string UpdateFlag = "";

            DataTable flagTbl = DAL.ExecuteQuery(sqlGetMemberFlag);
            if (flagTbl == null || flagTbl.Rows.Count == 0)
            {
                Logger.Log("Null result/0 rows when selecting " + ColumnName + " for MemberID '" + MemberID + "'! ASSUMING 'D' UPDATE!");
                UpdateFlag = "D";
            }
            else
            {
                string curFlag = "";
                if (flagTbl.Rows[0][ColumnName] == null)
                    curFlag = "";
                else
                    curFlag = flagTbl.Rows[0][ColumnName].ToString();

                switch (curFlag)
                {
                    case "A":
                        UpdateFlag = "";
                        break;
                    case "U":
                        UpdateFlag = "D";
                        break;
                    case "D":
                        UpdateFlag = null;
                        break;
                    default:
                        UpdateFlag = "D";
                        break;
                }
            }

            if (UpdateFlag != null) //Don't update if the current flag is already D
            {
                string sqlQry = string.Format(@"UPDATE memInfo SET {0}=@UpdateFlag WHERE MemberID=@MemberID",ColumnName);
                SqlParameter[] sParamArray = new SqlParameter[2];
                sParamArray[0] = new SqlParameter("@UpdateFlag", UpdateFlag) { SqlDbType = SqlDbType.Char, Size = 1 };
                sParamArray[1] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int};
                int updateResult = DAL.ExecuteNonQuery(sqlQry, sParamArray);
                if (updateResult != 1)
                {
                    Logger.Log("Updated " + ColumnName + "='" + UpdateFlag + "' for MemberID '" + MemberID + "' but no rows were affected! The " + ColumnName + " did not get updated!");
                    return false;
                }
            }
            return true;
        }

        public static void EnrollMember(int MemberID)
        {
            string oldFlagQuery = @"SELECT DedFlag FROM memInfo WHERE MemberID=@MemberID";
            SqlParameter[] sParamArray1 = new SqlParameter[1];
            sParamArray1[0] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            DataTable result1 = DAL.ExecuteQuery(oldFlagQuery, sParamArray1);
            if (result1 == null || result1.Rows.Count == 0)
                return;
            string oldFlag;
            if (result1.Rows[0]["DedFlag"] == null || result1.Rows[0]["DedFlag"] == DBNull.Value)
                oldFlag = "";
            else
                oldFlag = result1.Rows[0]["DedFlag"].ToString();

            string UpdateFlag = FlagMatrix("A", oldFlag);

            string sqlQry = @"UPDATE memInfo SET Enrolled=1, DedFlag=@DedFlag WHERE MemberID=@MemberID";
            SqlParameter[] sParamArray = new SqlParameter[2];
            sParamArray[0] = new SqlParameter("@DedFlag", UpdateFlag) { SqlDbType = SqlDbType.Char, Size = 1 };
            sParamArray[1] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            DAL.ExecuteNonQuery(sqlQry, sParamArray);
        }

        public static void UnenrollMember(int MemberID)
        {
            string oldFlagQuery = @"SELECT DedFlag FROM memInfo WHERE MemberID=@MemberID";
            SqlParameter[] sParamArray1 = new SqlParameter[1];
            sParamArray1[0] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            DataTable result1 = DAL.ExecuteQuery(oldFlagQuery, sParamArray1);
            if (result1 == null || result1.Rows.Count == 0)
                return;
            string oldFlag;
            if (result1.Rows[0]["DedFlag"] == null || result1.Rows[0]["DedFlag"] == DBNull.Value)
                oldFlag = "";
            else
                oldFlag = result1.Rows[0]["DedFlag"].ToString();

            string UpdateFlag = FlagMatrix("D", oldFlag);

            string sqlQry = @"UPDATE memInfo SET Enrolled=0, DedFlag=@DedFlag WHERE MemberID=@MemberID";
            SqlParameter[] sParamArray2 = new SqlParameter[2];
            sParamArray2[0] = new SqlParameter("@DedFlag", UpdateFlag) { SqlDbType = SqlDbType.Char, Size = 1 };
            sParamArray2[1] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            
            DAL.ExecuteNonQuery(sqlQry, sParamArray2);
        }

        public static bool CanUnenroll(int MemberID)
        {
            string sqlQry = @"SELECT COUNT(*) Plans FROM memPlans WHERE MemberID=@MemberID";
            SqlParameter[] sParamArray = new SqlParameter[1];
            sParamArray[0] = new SqlParameter("@MemberID", MemberID) { SqlDbType = SqlDbType.Int };
            DataTable result = DAL.ExecuteQuery(sqlQry, sParamArray);
            if (result == null || result.Rows.Count == 0)
                return false;
            if (((int)result.Rows[0]["Plans"]) == 0)
                return true;
            return false;

        }


        public static string FlagMatrix(string pnewFlag, string poldFlag)
        {

            string oldFlag = (pnewFlag ?? "").Trim();
            string newFlag = (poldFlag ?? "").Trim();

            string UpdateFlag = "";
            switch (oldFlag)
            {
                case "":
                    switch (newFlag)
                    {
                        case "":
                            UpdateFlag = "";
                            break;
                        case "A":
                            UpdateFlag = "A";
                            break;
                        case "U":
                            UpdateFlag = "A";
                            break;
                        case "D":
                            UpdateFlag = "";
                            break;
                    }
                    break;
                case "A":
                    switch (newFlag)
                    {
                        case "":
                            UpdateFlag = "A";
                            break;
                        case "A":
                            UpdateFlag = "A";
                            break;
                        case "U":
                            UpdateFlag = "A";
                            break;
                        case "D":
                            UpdateFlag = "";
                            break;
                    }
                    break;
                case "U":
                    switch (newFlag)
                    {
                        case "":
                            UpdateFlag = "U";
                            break;
                        case "A":
                            UpdateFlag = "U";
                            break;
                        case "U":
                            UpdateFlag = "U";
                            break;
                        case "D":
                            UpdateFlag = "D";
                            break;
                    }
                    break;
                case "D":
                    switch (newFlag)
                    {
                        case "":
                            UpdateFlag = "D";
                            break;
                        case "A":
                            UpdateFlag = "";
                            break;
                        case "U":
                            UpdateFlag = "U";
                            break;
                        case "D":
                            UpdateFlag = "D";
                            break;
                    }
                    break;
                default:
                    UpdateFlag = "";
                    Logger.Log("Encountered a FlagMatrix that wasn't '', 'A', 'U', or 'D'! Was: " + oldFlag + " New: " + newFlag);
                    break;
            }
            return UpdateFlag;
        }
    }
}
